package com.chentf.jdk;

import com.chentf.entity.User;
import com.chentf.struts2.service.UserService;
import com.chentf.struts2.service.impl.UserServiceImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author chentengfei
 * @desc ...
 * @date 2021-01-24 15:25:07
 */
public class TestJDKProxy {
    /*
        1.借用类加载器:TestJDKProxy  UserServiceImpl
        2.JDK8.X之前需要加final:
             final UserService userService = new UserServiceImpl();
     */
    public static void main(String[] args) {
        //1.创建原始对象
        UserService userService = new UserServiceImpl();
        //2.JDK创建动态代理
        InvocationHandler handler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("------proxy log------");
                //原始方法运行
                Object ret = method.invoke(userService, args);
                return ret;
            }
        };
        UserService userServiceProxy = (UserService) Proxy.newProxyInstance(TestJDKProxy.class.getClassLoader(), userService.getClass().getInterfaces(), handler);
        userServiceProxy.login("chentf", "123456");
        userServiceProxy.register(new User());
    }
}
